package org.component 
{
	import flash.events.EventDispatcher;
	import flash.display.MovieClip;
	import flash.geom.Rectangle;
	import flash.events.Event;
	
	import org.component.interfaces.IList;
	import org.component.interfaces.IListItem;
	
	/**
	 * ...
	 * @author kevin
	 */
	public class Hlist extends EventDispatcher implements IList
	{
		private var _assest:MovieClip = null;
		
		private var _classItem:Class = null; 
		
		private var _itemWidth:Number = 0;    
		private var _spaceWidth:Number = 0;
		
		private var _column:int = 1;
		private var _row:int = 1;
		
		private var _hslider:Hslider = null;
		
		private var _listView:MovieClip = null;
		
		private var _items:Array = null;
		
		public function Hlist(ui:MovieClip = null, item:Class = null, row:int=1, itemWidth:Number = 0, spaceWidth:Number=1) 
		{
			_assest = ui;
			_classItem = item;
			_row = row;
			
			_itemWidth = itemWidth;
			_spaceWidth = spaceWidth;
			
			initialization();
			configEventListeners();
		}
		
		/**
		 * 初始化
		 */
		protected function initialization():void
		{
			_hslider = new Hslider(_assest);
			
			_listView = _assest["listView"];
			
			_listView.scrollRect = new Rectangle(0, 0, _listView.width, _listView.height + 1);
			
			_items = [];
			
			for (var i:int = 0; i < _row; i++)
			{
				var item:IListItem = new _classItem(_listView["item" + i]) as IListItem;
				_items[_items.length] = item;
			}
		}
		
		private var _list:Array = null;
		/**
		 * 
		 * @param	list
		 */
		public function update(list:Array = null):void
		{
			_list = list?list:[];
			_hslider.update(_row, _list.length);
			onChange(null);
		}
		
		/**
		 * 注册监听
		 */
		protected function configEventListeners():void
		{
			_hslider.addEventListener(Event.CHANGE, onChange);
			
		}
		
		private function onChange(event:Event):void
		{
			index = _hslider.itemIndex;
		}	
		
		private function setNewList(_line:int = 0):void
		{
			var j:int = 0;
			var pos:Number = _itemWidth * _line;
	
			for (var i:int = _line; i < (_row + _line); i++)	
			{
				var listItem:IListItem = _items[j];

				if (_list[i] != null)
				{
					if (listItem.index != i) listItem.index = i;
					listItem.update(_list[i]);

				}else
				{
					listItem.dispose();
				}

				pos += _itemWidth;
				j++;
			}
		}
		
		private var _index:int = -1;
		public function get index():int { return _index; }
		public function set index(value:int):void
		{
			if (_index == value) return;
			
			_index = value;
			setNewList(index);
		}
	}
}